import tensorflow as tf
from captcha.image import ImageCaptcha
import numpy as np
from PIL import Image
import random
import math

'''定义验证码，数字+小写字母+大写字母'''
number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
            'v', 'w', 'x', 'y', 'z']
ALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
            'V', 'W', 'X', 'Y', 'Z', '_']


def random_captcha_text(char_set_=number + alphabet + ALPHABET, captcha_size=4):
    '''
   随机生成验证码数
   :param char_set_:验证码树集合
   :param captcha_size: 验证码位数
   :return: 验证码
   '''
    captcha_text = []
    for i in range(captcha_size):
        c = random.choice(char_set_)
        captcha_text.append(c)
    return captcha_text


def gen_captcha_text_and_image():
    '''等到一副验证码图
    :return:captcha_text: 验证码文字和captcha_image:验证码图
    '''
    _image = ImageCaptcha()
    captcha_text = random_captcha_text(char_set_=char_set)
    captcha_text = ''.join(captcha_text)
    captcha = _image.generate(captcha_text)
    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image


def convert2gray(img):
    '''讲验证码图转换成灰度图
    :param img: 验证码图
    :return: 灰度图
    '''
    if len(img.shape) > 2:
        r, g, b = img[:, :, 0], img[:, :, 1], img[:, :, 2]
        gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
        return gray
    else:
        return img


def text2vec(_text):
    '''讲字符型全部转换成数字型
    :param _text: 验证码文字
    :return: 转换成数字向量
    '''
    text_len = len(_text)
    if text_len > MAX_CAPTCHA:
        raise ValueError('验证码最长4个字符')
    vector = np.zeros(MAX_CAPTCHA * CHAR_SET_LEN)

    def char2pos(character):
        if character == '_':
            k = 62
            return k
        k = ord(character) - 48
        if k > 9:
            k = ord(character) - 55
            if k > 35:
                k = ord(character) - 61
                if k > 61:
                    raise ValueError('No Map')
        return k

    for i, c in enumerate(_text):
        idx = i * CHAR_SET_LEN + char2pos(c)
        vector[idx] = 1
    return vector


def vec2text(vec):
    '''讲向量装换成文本
    :param vec: 数字向量
    :return: 验证码文字
    '''
    char_pos = vec.nonzero()[0]
    char_text = []
    for i, c in enumerate(char_pos):
        char_idx = c % CHAR_SET_LEN
        if char_idx < 10:
            char_code = char_idx + ord('0')
        elif char_idx < 36:
            char_code = char_idx - 10 + ord('A')
        elif char_idx < 62:
            char_code = char_idx - 36 + ord('a')
        elif char_idx == 62:
            char_code = ord('_')
        else:
            raise ValueError('error')
        char_text.append(chr(char_code))
    return "".join(char_text)


def get_next_batch(batch_size=128):
    '''生成一个训练
    :param batch_size: batch的大小
    :return: 讲batch的x，y向量返回
    '''
    batch_x = np.zeros([batch_size, IMAGE_HEIGHT * IMAGE_WIDTH])
    batch_y = np.zeros([batch_size, MAX_CAPTCHA * CHAR_SET_LEN])

    # 有时生成图像大小不是(60, 160, 3)
    def wrap_gen_captcha_text_and_image():
        while True:
            t, img = gen_captcha_text_and_image()
            if image.shape == (60, 160, 3):
                return t, img

    for i in range(batch_size):
        text_, image_ = wrap_gen_captcha_text_and_image()
        image_ = convert2gray(image_)
        batch_x[i, :] = image_.flatten() / 255
        batch_y[i, :] = text2vec(text_)
    return batch_x, batch_y


def crack_captcha_cnn(w_alpha=0.01, b_alpha=0.1):
    '''定义三层卷积神经网络
    :param w_alpha: 权重
    :param b_alpha: 偏置
    :return:
    '''

    x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1])

    w_c1 = tf.Variable(w_alpha * tf.random_normal([3, 3, 1, 32]))
    b_c1 = tf.Variable(b_alpha * tf.random_normal([32]))
    rel_1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1))
    pool_1 = tf.nn.max_pool(rel_1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    con_1 = tf.nn.dropout(pool_1, keep_prob)

    w_c2 = tf.Variable(w_alpha * tf.random_normal([3, 3, 32, 64]))
    b_c2 = tf.Variable(b_alpha * tf.random_normal([64]))
    rel_2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(con_1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2))
    pool_2 = tf.nn.max_pool(rel_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    con_2 = tf.nn.dropout(pool_2, keep_prob)

    w_c3 = tf.Variable(w_alpha * tf.random_normal([3, 3, 64, 64]))
    b_c3 = tf.Variable(b_alpha * tf.random_normal([64]))
    rel_3 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(con_2, w_c3, strides=[1, 1, 1, 1], padding='SAME'), b_c3))
    pool_3 = tf.nn.max_pool(rel_3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    con_3 = tf.nn.dropout(pool_3, keep_prob)

    w_d = tf.Variable(w_alpha * tf.random_normal([8 * 20 * 64, 1024]))
    b_d = tf.Variable(b_alpha * tf.random_normal([1024]))
    dense = tf.reshape(con_3, [-1, w_d.get_shape().as_list()[0]])
    rel = tf.nn.relu(tf.add(tf.matmul(dense, w_d), b_d))
    dense = tf.nn.dropout(rel, keep_prob)

    w_out = tf.Variable(w_alpha * tf.random_normal([1024, MAX_CAPTCHA * CHAR_SET_LEN]))
    b_out = tf.Variable(b_alpha * tf.random_normal([MAX_CAPTCHA * CHAR_SET_LEN]))
    out = tf.add(tf.matmul(dense, w_out), b_out)
    return out


def train_crack_captcha_cnn(step=0):
    '''开始训练
    :return: 训练好的模型讲保存下来
    '''
    output = crack_captcha_cnn()
    loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=Y))
    learning_rate = 0.01
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
    predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])
    max_idx_l = tf.argmax(tf.reshape(Y, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
    correct_pre = tf.equal(tf.argmax(predict, 2), max_idx_l)
    accuracy = tf.reduce_mean(tf.cast(correct_pre, tf.float32))
    saver = tf.train.Saver()
    losses_ = 100
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        while True:
            batch_x, batch_y = get_next_batch(150)
            _, losses = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.75})
            print('loss:', losses)
            if step % 5 == 0:
                batch_x_test, batch_y_test = get_next_batch(50)
                acc = sess.run(accuracy, feed_dict={X: batch_x_test, Y: batch_y_test, keep_prob: 1.})
                print(step, '精度:', acc)
                if losses > losses_:
                    learning_rate -= learning_rate / math.e
                    print(learning_rate)
                losses_ = losses
                if acc > 0.900:
                    saver.save(sess, "./model/captcha.model", global_step=0)
                    break
            step += 1


def reader_captcha(captcha_image):
    '''
    读取模型
    :param captcha_image: 验证码图片
    :return: 识别的验证码文字
    '''
    output = crack_captcha_cnn()
    saver = tf.train.Saver()
    with tf.Session() as sess:
        saver.restore(sess, "./model/captcha.model-0")
        predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
        text_list = sess.run(predict, feed_dict={X: [captcha_image], keep_prob: 1})
        return text_list[0].tolist()


IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160

# 验证码包含数字+大小写字母
# char_set = number + alphabet + ALPHABET

# 验证码只包含数字
char_set = number

CHAR_SET_LEN = len(char_set)
text, image = gen_captcha_text_and_image()
MAX_CAPTCHA = len(text)
X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT * IMAGE_WIDTH])
Y = tf.placeholder(tf.float32, [None, MAX_CAPTCHA * CHAR_SET_LEN])
keep_prob = tf.placeholder(tf.float32)
